package com.itcast.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.itcast.logic.MainService;
import com.itcast.logic.Task;
import com.itcast.ui.R;
import com.itcast.ui.CommentActivity.MyAdapter;
import com.itcast.util.TextViewLink;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import weibo4android.Status;
import weibo4android.Trend;
import weibo4android.Trends;
import weibo4android.User;
import weibo4android.WeiboException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class RedirectActivity extends Activity implements TextWatcher,
OnClickListener{
	private View title;
	private Button back, send;
	private TextView titleTv, tvCmtLabel, trend, mention, emotion;
	private EditText editText;
	private CheckBox rb_forward;
	private GridView myGridView;
	private long id = 0;
	private ListView myListView;
	private ArrayList<HashMap<String, String>> myList;
	private SimpleAdapter mSchedule;
	public static MyAdapter myAdapter;
	private Status status;

	

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		try {
			status = (Status) getIntent().getSerializableExtra("status");
			if (status == null) {
				finish();
						 }
			} catch (Exception e) {
			Log.e("RedirectActivity", "onCreate");
			finish();
		}

		setContentView(R.layout.comment);

		title = findViewById(R.id.title);
		titleTv = (TextView) findViewById(R.id.textView);
		titleTv.setText("转发微博");
		back = (Button) findViewById(R.id.title_bt_left);
		back.setText(R.string.imageviewer_back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (myGridView.getVisibility() == View.VISIBLE) {
					myGridView.setVisibility(View.GONE);
				} else if (myListView.getVisibility() == View.VISIBLE) {
					myListView.setVisibility(View.GONE);
				} else if (editText.getText().toString().length() != 0) {
					dialog();
				} else
					finish();
			
			}

		});

		send = (Button) findViewById(R.id.title_bt_right);
		send.setText(R.string.title_button_send);
		send.setOnClickListener(this);
		editText = (EditText) findViewById(R.id.etCmtReason);
		editText.setHeight(300);
		String originalText = "//@"+status.getUser().getName()+": "+status.getText();
		editText.setText(TextViewLink.addURLSpan(originalText, null, this));
		editText.requestFocus(); 
		editText.setSelection(0);
		//必须要先setText，再addListener
		editText.addTextChangedListener(this);
		

		
		
		tvCmtLabel = (TextView) findViewById(R.id.tvCmtLabel);
		int restNum = 140 - originalText.length();
		tvCmtLabel.setText("" + restNum);
		rb_forward = (CheckBox) findViewById(R.id.rb_forward);

		myGridView = (GridView) findViewById(R.id.myGridView);
		myListView = (ListView) findViewById(R.id.myListView);
		trend = (TextView) findViewById(R.id.trend);
		mention = (TextView) findViewById(R.id.mention);
		emotion = (TextView) findViewById(R.id.emotion);
		// myListView.setOnScrollListener(new ScrollListener());

		trend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editText.setHeight(50);
				toTrend();
			}
		});

		mention.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editText.setHeight(50);
				toMention();
			}
		});

		emotion.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editText.setHeight(250);
				toEmotion();
			}
		});

	}

	protected void toEmotion() {
		//下边2句注释掉代码表示进行下载获取
//		Task ts = new Task(Task.TASK_GET_EXPRESSION_IMAGE_ICON, null);
//		MainService.addNewTask(ts);

		
		myGridView.setVisibility(View.VISIBLE);
		myGridView.setNumColumns(6);
		//初始化adapter和CommentActivity的handler
		CommentActivity.myAdapter = new MyAdapter(this);
		myGridView.setAdapter(CommentActivity.myAdapter);
		if(CommentActivity.handler == null)
		CommentActivity.handler = new Handler(){
			@Override
			//当有消息发送出来的时候就执行Handler的这个方法
			public void handleMessage(Message msg){
			super.handleMessage(msg);
			CommentActivity.myAdapter.notifyDataSetChanged();
			}
			};

		OnItemClickListener itemListener = new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				final String message = "OnTouchGrid:Icon No." + id
						+ " is Touched.";
				Toast.makeText(getApplicationContext(), message, 1000).show();

				editText.setHeight(300);

				 // 得到drawable对象，即所有插入的图片
				Drawable d = getResources().getDrawable(CommentActivity.myAdapter.imgs[position]);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				// 用这个drawable对象代替字符串
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				String picName = getResources().getResourceName(CommentActivity.myAdapter.imgs[position]).split("/")[1];
				String phrase ="["+ TextViewLink.getPicDescription(picName, getApplicationContext()) +"]";
				SpannableString ss = new SpannableString(phrase);
				// 包括0但是不包括phrase.length()
				ss.setSpan(span, 0, ss.length(),
						Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
				editText.append(ss);
				
				myGridView.setVisibility(View.GONE);
			}
		};
		myGridView.setOnItemClickListener(itemListener);
	}

	protected void toMention() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "mention", Toast.LENGTH_LONG)
				.show();
		// editText.setHeight(20);

		// 绑定XML中的ListView，作为Item的容器
		
		myListView.setVisibility(View.VISIBLE);
		// 生成动态数组
		myList = new ArrayList<HashMap<String, String>>();
		List<User> userList = null;
		try {
			userList = MainService.mainService.weibo.getFriendsStatuses();
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("friendName", "@");
		myList.add(map);
		for (int i = 0; i < userList.size(); i++) {
			User friend = userList.get(i);
			String name = friend.getName();
			map = new HashMap<String, String>();
			map.put("friendName", name);
			myList.add(map);
			Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT)
					.show();
		}

		// 生成适配器，数组===》ListItem
		mSchedule = new SimpleAdapter(this, // 没什么解释
				myList,// 数据来源
				R.layout.friend_item,// ListItem的XML实现
				// 动态数组与ListItem对应的子项
				new String[] { "friendName" },

				// ListItem的XML文件里面的TextView ID
				new int[] { R.id.friend });

		myListView.setAdapter(mSchedule);
		myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				String friendName = (String) myList.get(arg2).get("friendName");

				Toast.makeText(getApplicationContext(),
						"你点击了" + arg2 + "项的" + friendName, Toast.LENGTH_SHORT)
						.show();
				editText.setHeight(300);
				if (friendName == "@")
					editText.append("@");
				else
					editText.append("@" + friendName + " ");

				myListView.setVisibility(View.GONE);
			}
		});

	}

	protected void toTrend() {
		// TODO Auto-generated method stub

		// 绑定XML中的ListView，作为Item的容器
		myListView.setVisibility(View.VISIBLE);

		List<Trends> trendList = null;
		try {
			trendList = MainService.mainService.weibo.getTrendsWeekly(0);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HashMap<String, String> map = new HashMap<String, String>();
		// 生成动态数组
		myList = new ArrayList<HashMap<String, String>>();
		map.put("friendName", "##");
		myList.add(map);
		for (int i = 0; i < trendList.size(); i++) { // 事实上，这里的trendList.size()�?
			Trends trend = trendList.get(i);
			Trend[] news = trend.getTrends();
			for (int j = 0; j < news.length; j++) {
				String trendName = news[j].getName();
				map = new HashMap<String, String>();
				map.put("friendName", trendName);
				myList.add(map);
				Toast.makeText(getApplicationContext(), trendName,
						Toast.LENGTH_LONG).show();
			}
		}
		// 生成适配器，数组===》ListItem
		mSchedule = new SimpleAdapter(this, // 没什么解释
				myList,// 数据来源
				R.layout.friend_item,// ListItem的XML实现
				// 动态数组与ListItem对应的子项
				new String[] { "friendName" },

				// ListItem的XML文件里面的TextView ID
				new int[] { R.id.friend });

		myListView.setAdapter(mSchedule);
		myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				String friendName = (String) myList.get(arg2).get("friendName");

				Toast.makeText(getApplicationContext(),
						"你点击了" + arg2 + "项的" + friendName, Toast.LENGTH_SHORT)
						.show();

				editText.setHeight(300);
				if (friendName == "##") {
					editText.append("##");
					editText.requestFocus();
					editText.setSelection(editText.length() - 1);
				} else
					editText.append("#" + friendName + "# ");

				myListView.setVisibility(View.GONE);
			}
		});
	}

	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		int i = 140 - arg0.length();
		tvCmtLabel.setText("" + i);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if( editText.getText().length() <= 140 ){
		HashMap hm = new HashMap();
		String content = editText.getText().toString();
		hm.put("msg", content);
		hm.put("id", String.valueOf(status.getId()));
		if (rb_forward.isChecked()) {
			hm.put("newc", new Boolean(true));
		} else {
			hm.put("newc", new Boolean(false));
		}
		Task ts = new Task(Task.TASK_NEW_WEIBO_REDIRECT, hm);
		MainService.addNewTask(ts);
		finish();
		} 
		else
			Toast.makeText(getApplicationContext(), "字数超出限制", 3000).show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	public void afterTextChanged(Editable arg0) {
	}

	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (myGridView.getVisibility() == View.VISIBLE) {
				myGridView.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(),
						myGridView.getVisibility() + "", 3000).show();
				return false; 
			} else if (myListView.getVisibility() == View.VISIBLE) {
				myListView.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(),
						myGridView.getVisibility() + "", 3000).show();
				return false;
			} else if (editText.getText().toString().length() != 0) {
				dialog();
				return false;
			} else
				return super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	//在退出前进行询问
	protected void dialog() {
		AlertDialog.Builder builder = new Builder(RedirectActivity.this);
		builder.setMessage("确定要退出编辑吗?");
		builder.setTitle("提示");
		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						arg0.dismiss();
						RedirectActivity.this.finish();
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}
}
